package com.shuoyue.ycgk.ui.questionbank.search;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.HotSearch;
import com.shuoyue.ycgk.entity.QuestionSimple;
import com.shuoyue.ycgk.net.exception.NetErrorException;
import com.shuoyue.ycgk.ui.common.VipCheckContract;
import com.shuoyue.ycgk.ui.mine.vip.MyVipActivity;
import com.shuoyue.ycgk.ui.search.HisAdapter;
import com.shuoyue.ycgk.ui.search.HotAdapter;
import com.shuoyue.ycgk.ui.search.SerchContract;
import com.shuoyue.ycgk.utils.GridSpacingItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchQuestionActivity extends BaseMvpActivity<SearchContract.Presenter>
        implements SearchContract.View, VipCheckContract.View {

    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.total_num)
    TextView totalNum;
    @BindView(R.id.search_title)
    TextView searchTitle;
    @BindView(R.id.search_info_layout)
    LinearLayout searchInfoLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refreshlayout)
    SmartRefreshLayout refreshlayout;
    @BindView(R.id.search_his)
    RecyclerView searchHis;
    @BindView(R.id.search_hot)
    RecyclerView searchHot;
    @BindView(R.id.lay_searchTips)
    LinearLayout laySearchTips;
    //    @BindView(R.id.ck_all)
//    CheckBox ckAll;
    @BindView(R.id.ck_title)
    CheckBox ckTitle;
    @BindView(R.id.ck_option)
    CheckBox ckOption;
    @BindView(R.id.ck_aly)
    CheckBox ckAly;

    String title = "";
    int modelId = -1;
    int subjectTypeId = -1;
    ListWithPage listWithPage;
    QuestionSearchAdapter adapter;
    VipCheckContract.Presenter vipCheckPresenter;
    boolean isVip = false;
    List<String> his = new ArrayList<>();
    HisAdapter hisAdapter;
    HotAdapter hotAdapter;

    Integer searchType = null;

    public static void start(Context sourse, int modelId, int subjectTypeId) {
        sourse.startActivity(new Intent(sourse, SearchQuestionActivity.class)
                .putExtra("modelId", modelId)
                .putExtra("subjectTypeId", subjectTypeId));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_question;
    }

    @Override
    protected void initView() {
        searchHis.setLayoutManager(new FlexboxLayoutManager(mContext));
        searchHis.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtil.dip2px(mContext, 8), false));
        searchHot.setLayoutManager(new FlexboxLayoutManager(mContext));
        searchHot.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtil.dip2px(mContext, 8), false));

        hisAdapter = new HisAdapter(null);
        hotAdapter = new HotAdapter(null);
        searchHis.setAdapter(hisAdapter);
        searchHot.setAdapter(hotAdapter);

        hisAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            String title = (String) adapter.getItem(position);
            edit.setText(title);
            this.title = title;
            listWithPage = null;
            mPresenter.searchQuestion(getSearchType(), title, modelId, 1);
            laySearchTips.setVisibility(View.GONE);
        });
        hotAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            HotSearch title = (HotSearch) adapter.getItem(position);
            edit.setText(title.getSearchName());
            this.title = title.getSearchName();
            listWithPage = null;
            mPresenter.searchQuestion(getSearchType(), title.getSearchName(), modelId, 1);
            laySearchTips.setVisibility(View.GONE);
        });
        edit.setOnEditorActionListener((v, actionId, event) -> {
            title = edit.getText().toString();
            if (!TextUtils.isEmpty(title)) {
                vipCheckPresenter.checkVip(subjectTypeId);
                mPresenter.searchQuestion(getSearchType(), title, modelId, 1);
                changeHis(title);
                laySearchTips.setVisibility(View.GONE);

            }
            return false;
        });
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                title = s.toString();
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 2), false));

        adapter = new QuestionSearchAdapter(null);
        recyclerView.setAdapter(adapter);
        refreshlayout.setEnableLoadMore(false);
        refreshlayout.setOnLoadMoreListener(refreshLayout -> {
            if (!TextUtils.isEmpty(title) && listWithPage != null) {
                mPresenter.searchQuestion(getSearchType(), title, modelId, listWithPage.getCurrent() + 1);
            } else {
                XToast.toast(mContext, "请输入搜索关键字");
            }
            refreshLayout.finishLoadMore();
        });
        refreshlayout.setOnRefreshListener(refreshLayout -> {
            if (!TextUtils.isEmpty(title)) {
                mPresenter.searchQuestion(getSearchType(), title, modelId, 1);
            } else {
                XToast.toast(mContext, "请输入搜索关键字");
            }
            refreshLayout.finishRefresh();
        });
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            QuestionSimple questionSimple = (QuestionSimple) adapter.getItem(position);
            switch (view.getId()) {
                case R.id.collection:
                    if (isVip) {
                        if (questionSimple.getIsCollect() == 0) {
                            mPresenter.saveCollect(questionSimple);
                        } else {
                            mPresenter.deleteCollection(questionSimple);
                        }
                    } else {
                        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "一锤温馨提示", "购买会员后解锁收藏");
                        hintConfirmDialog.setButtonText("取消", "立即购买");
                        hintConfirmDialog.setOkListener(v -> startActivity(new Intent(mContext, MyVipActivity.class)));
                        hintConfirmDialog.show();
//                        XToast.toast(mContext, "购买会员可收藏题目");
                    }

                    break;
                case R.id.check_aly:
                    if (isVip) {
                        questionSimple.setShowRight(!questionSimple.isShowRight());
                        adapter.notifyDataSetChanged();
                    } else {
                        HintConfirmDialog hintConfirmDialog =
                                new HintConfirmDialog(mContext, "一锤温馨提示", "购买会员后解锁查看解析");
                        hintConfirmDialog.setButtonText("取消", "立即购买");
                        hintConfirmDialog.setOkListener(v -> startActivity(new Intent(mContext, MyVipActivity.class)));
                        hintConfirmDialog.show();
//                        XToast.toast(mContext, "购买会员可查看解析");
                    }
                    break;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        vipCheckPresenter.checkVip(subjectTypeId);
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter = new SearchContract.Presenter();
        mPresenter.attachView(this);
        vipCheckPresenter = new VipCheckContract.Presenter();
        vipCheckPresenter.attachView(this);
        modelId = getIntent().getIntExtra("modelId", -1);
        subjectTypeId = getIntent().getIntExtra("subjectTypeId", -1);
        if (subjectTypeId != -1) {
            vipCheckPresenter.checkVip(subjectTypeId);
        }
        initHis();
        mPresenter.searchHot();
    }

    void initHis() {
        Gson gson = new Gson();
        String data = "[]";
        data = SPUtils.getPrefString(mContext, "search_his_q", "[]");
        his = gson.fromJson(data, new TypeToken<List<String>>() {
        }.getType());
        hisAdapter.setNewData(his);

    }

    void changeHis(String newStr) {
        if (his == null) {
            his = new ArrayList<>();
        }
        if (his.contains(newStr)) {
            return;
        }
        List<String> saveData = new ArrayList<>();
        saveData.add(newStr);

        if (his.size() < 6) {
            saveData.addAll(his);
        } else {
            saveData.addAll(his.subList(0, 5));
        }
        Gson gson = new Gson();
        String dataStr = gson.toJson(saveData);
        SPUtils.setPrefString(mContext, "search_his_q", dataStr);
        hisAdapter.setNewData(saveData);
        his = saveData;
    }

    void clearHis() {
        his.clear();
        hisAdapter.notifyDataSetChanged();
        SPUtils.setPrefString(mContext, "search_his_q", "[]");
    }

    @Override
    public void searchResult(ListWithPage<QuestionSimple> ques) {
        recyclerView.setVisibility(View.VISIBLE);
        this.listWithPage = ques;
        if (ques.getCurrent() == 1) {
            adapter.resetData(ques.getRecords());
        } else {
            adapter.addData(ques.getRecords());
        }
        refreshlayout.setEnableLoadMore(ques.getCurrent() != ques.getPages() && ques.getPages() > 0);
        searchInfoLayout.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.VISIBLE);
        totalNum.setText(String.valueOf(ques.getTotal()));
        searchTitle.setText(title);
        refreshlayout.finishLoadMore();
        refreshlayout.finishRefresh();
    }

    @Override
    public void addCollectSuc(QuestionSimple questionSimple) {
        questionSimple.setIsCollect(1);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void deleteCollectSuc(QuestionSimple questionSimple) {
        questionSimple.setIsCollect(0);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void searchHotSuc(List<HotSearch> hots) {
        hotAdapter.setNewData(hots);
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void isVip(int isVip) {
        this.isVip = isVip == 1;
    }

    @Override
    public void onError(NetErrorException throwable) {
//        super.onError(throwable);
    }


    @OnClick({R.id.back, R.id.delete, R.id.x, R.id.ck_title, R.id.ck_option, R.id.ck_aly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.delete:
                clearHis();
                break;

            case R.id.x:
                edit.setText("");
                laySearchTips.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
                adapter.clear();
                break;
//            case R.id.ck_all:
//                ckTitle.setChecked(ckAll.isChecked());
//                ckOption.setChecked(ckAll.isChecked());
//                ckAly.setChecked(ckAll.isChecked());
//                break;
            case R.id.ck_title:
            case R.id.ck_option:
            case R.id.ck_aly:
                handler.removeCallbacks(task);
                handler.postDelayed(task, 1000);
                break;
        }
        registEmptyView(adapter);
    }

    Handler handler = new Handler();
    Runnable task = new Runnable() {
        @Override
        public void run() {
            mPresenter.searchQuestion(getSearchType(), title, modelId, 1);
        }
    };

    String getSearchType() {
        StringBuilder sb = new StringBuilder();

        if (ckTitle.isChecked()) {
            sb.append("1");
        }
        if (ckOption.isChecked()) {
            if (sb.length() != 0) {
                sb.append(",");
            }
            sb.append("3");
        }
        if (ckAly.isChecked()) {
            if (sb.length() != 0) {
                sb.append(",");
            }
            sb.append("2");
        }
        return sb.toString().length() == 0 ? "1,2,3" : sb.toString();
    }

}
